import { isNil } from 'lodash-es'
import type { CacheData, CacheKey, CacheResult } from './types'

const cacheMap = new Map<CacheKey, CacheResult>()

export const getCache = (cacheKey: CacheKey) => {
  if (isNil(cacheKey)) return
  const data = cacheMap.get(cacheKey)
  return data
}

export const setCache = (cacheKey: CacheKey, cacheTime: number, data: CacheData) => {
  const oldCache = cacheMap.get(cacheKey)
  if (oldCache && oldCache.timer) {
    clearTimeout(oldCache.timer)
  }
  const timer = setTimeout(() => cacheMap.delete(cacheKey), cacheTime)
  cacheMap.set(cacheKey, { ...data, timer })
}

export const clearCache = (cacheKey?: CacheKey) => {
  if (cacheKey) {
    const timer = cacheMap.get(cacheKey)?.timer
    timer && clearTimeout(timer)
    cacheMap.delete(cacheKey)
  } else {
    cacheMap.forEach(cache => cache.timer && clearTimeout(cache.timer))
    cacheMap.clear()
  }
}
